<div id="userBox" class="pull-right"><!-- temp css --> <?php 
require("resources/const.php");
require_once("library/curl.php");

function drawLoggedIn($content) {
    return $content;
}

function loggedIn() {
    return isset($_SESSION['uid']) && $_SESSION['uid'] > 0;
}

function remoteLoggedIn() {
    $BACKEND_URL = $_SERVER['HTTP_HOST'];
    $curl = new curlHelper();
    $curl->addHandle($BACKEND_URL."/api/auth/session.php","drawLoggedIn");
    $tmp = $curl->exec();
    return $tmp;
}

function login($uid, $sid) {
    $_SESSION['uid'] = $uid;
    $_SESSION['sid'] = $sid;
    checkStatus();
}

function drawLogin($content) {
    if (isset($content["redirect"])) {
        $_SESSION['sid'] = $content['sid'];
        header("location:".$content["redirect"]);
    } elseif ($content["status"]=="ok") {
        login();
    }
}

function remoteLogin() {
    $BACKEND_URL = $_SERVER['HTTP_HOST'];
    $curl = new curlHelper();
    $curl->addHandle($BACKEND_URL."/api/auth/login.php","drawLogin",
    array("return"=>'http://'.$_SERVER['HTTP_HOST']),true);
    $curl->exec();
}

function remoteLogout() {
    $BACKEND_URL = $_SERVER['HTTP_HOST'];
    $curl = new curlHelper();
    $curl->addHandle($BACKEND_URL."/api/auth/logout.php","logout");
    $curl->exec();
}

function logout($content = null) {
    $_SESSION['uid'] = 0;
    $_SESSION['sid'] = 0;
    checkStatus();
}

function drawProfile($content) {
    if ($content["status"]=="ok") {
        $profileBox_username = $content["name"];
        require "modules/interfaces/profileBox.php";
    } else {
        logOut(true);
    }
}

function checkStatus() {
    $rlog = remoteLoggedIn();//shallow copies in php?
    if ($rlog["status"]=="ok") {
        if (loggedIn()) {
            $curl = new curlHelper();
            $BACKEND_URL = $_SERVER['HTTP_HOST'];
            $curl->addHandle("$BACKEND_URL/api/auth/profile.php","drawProfile");
            $curl->exec();
        }else {
            login($rlog['userid'],$rlog['sid']);
        }
    } elseif (loggedIn()) {
        logout();
    }else {
        require("modules/loginBox.php");
    }
}
checkStatus();
?></div>
